package com.training.player;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.annotation.OptIn;
import androidx.core.app.NotificationCompat;

import androidx.media3.common.MediaItem;
import androidx.media3.common.Player;
import androidx.media3.common.util.UnstableApi;
import androidx.media3.datasource.DataSource;
import androidx.media3.datasource.DefaultDataSource;
import androidx.media3.exoplayer.ExoPlayer;
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory;

public class PlayerService extends android.app.Service {
    private static final String CHANNEL_ID = "media_playback_channel";
    private static final int NOTIFICATION_ID = 1;
    private static final String TAG = "PlayerService";

    private ExoPlayer player;
    private final IBinder binder = new LocalBinder();
    private NotificationManager notificationManager;
    
    // 添加播放状态变化监听器
    private Player.Listener playerListener;

    // 播放控制动作
    public static final String ACTION_PLAY = "com.training.action.PLAY";
    public static final String ACTION_PAUSE = "com.training.action.PAUSE";
    public static final String ACTION_STOP = "com.training.action.STOP";
    
    // 添加播放状态变化广播
    public static final String ACTION_PLAYBACK_STATE_CHANGED = "com.training.action.PLAYBACK_STATE_CHANGED";

    public class LocalBinder extends Binder {
        public PlayerService getService() {
            return PlayerService.this;
        }
    }

    @OptIn(markerClass = UnstableApi.class) @Override
    public void onCreate() {
        super.onCreate();

        // 初始化通知管理器
        notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        // 创建通知渠道
        createNotificationChannel();

        // 初始化 ExoPlayer 并配置支持加密音频的DataSource
        // 创建自定义加密数据源工厂
        DefaultDataSource.Factory dataSourceFactory = new DefaultDataSource.Factory(this, 
                new DataSource.Factory() {
                    @Override
                    public DataSource createDataSource() {
                        return new EncryptedDataSource("ExoPlayer-TrainingApp");
                    }
                });
        
        player = new ExoPlayer.Builder(this)
                .setMediaSourceFactory(new DefaultMediaSourceFactory(dataSourceFactory))
                .build();
        
        // 添加播放器事件监听器
        playerListener = new Player.Listener() {
            @Override
            public void onIsPlayingChanged(boolean isPlaying) {
                // 播放状态变化时更新通知和发送广播
                updateNotification();
                // 发送广播通知播放状态变化
                Intent intent = new Intent(ACTION_PLAYBACK_STATE_CHANGED);
                intent.putExtra("isPlaying", isPlaying);
                sendBroadcast(intent);
            }
            
            @Override
            public void onPlayerError(@Nullable androidx.media3.common.PlaybackException error) {
                if (error != null) {
                    Log.e(TAG, "播放器错误: " + error.getMessage(), error);
                    Toast.makeText(PlayerService.this, "播放错误: " + error.getMessage(), Toast.LENGTH_LONG).show();
                }
            }
        };
        player.addListener(playerListener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (intent != null) {
            String action = intent.getAction();

            // 处理广播命令
            if (PlayerService.ACTION_PLAY.equals(action)) {
                resumeMedia();
            } else if (PlayerService.ACTION_PAUSE.equals(action)) {
                pauseMedia();
            } else if (PlayerService.ACTION_STOP.equals(action)) {
                stopSelf();
            }

            // 处理传入的播放指令
            if (intent.getStringExtra("audio_url") != null) {
                String mediaUrl = intent.getStringExtra("audio_url");
                playMedia(mediaUrl);
            }
        }

        return START_STICKY; // 服务被杀死后会重启
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public void playMedia(String mediaUrl) {
        try {
            Log.d(TAG, "尝试播放音频: " + mediaUrl);
            // 准备媒体项
            MediaItem mediaItem = new MediaItem.Builder()
                    .setUri(mediaUrl)
                    .build();
            player.setMediaItem(mediaItem);
            player.prepare();
            player.play();

            // 显示播放通知
            startForeground(NOTIFICATION_ID, buildNotification());
        } catch (Exception e) {
            Log.e(TAG, "播放音频时出错: " + e.getMessage(), e);
            Toast.makeText(this, "播放失败: " + e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    public void pauseMedia() {
        if (player != null && player.isPlaying()) {
            player.pause();
            // 更新通知状态
            updateNotification();
            // 发送广播通知播放状态变化
            Intent intent = new Intent(ACTION_PLAYBACK_STATE_CHANGED);
            intent.putExtra("isPlaying", false);
            sendBroadcast(intent);
        }
    }

    public void resumeMedia() {
        if (player != null && !player.isPlaying()) {
            player.play();
            // 更新通知状态
            updateNotification();
            // 发送广播通知播放状态变化
            Intent intent = new Intent(ACTION_PLAYBACK_STATE_CHANGED);
            intent.putExtra("isPlaying", true);
            sendBroadcast(intent);
        }
    }

    public boolean isPlaying() {
        return player != null && player.isPlaying();
    }

    public ExoPlayer getPlayer() {
        return player;
    }

    // 创建通知渠道
    private void createNotificationChannel() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID,
                    "Media Playback",
                    NotificationManager.IMPORTANCE_LOW
            );
            channel.setDescription("Media playback controls");
            notificationManager.createNotificationChannel(channel);
        }
    }

    // 构建通知
    private Notification buildNotification() {
        // 创建播放意图
        Intent playIntent = new Intent(this, PlayerService.class);
        playIntent.setAction(ACTION_PLAY);
        PendingIntent playPendingIntent = PendingIntent.getService(
                this, 0, playIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 创建暂停意图
        Intent pauseIntent = new Intent(this, PlayerService.class);
        pauseIntent.setAction(ACTION_PAUSE);
        PendingIntent pausePendingIntent = PendingIntent.getService(
                this, 0, pauseIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 创建停止意图
        Intent stopIntent = new Intent(this, PlayerService.class);
        stopIntent.setAction(ACTION_STOP);
        PendingIntent stopPendingIntent = PendingIntent.getService(
                this, 0, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_IMMUTABLE);

        // 根据播放状态设置内容文本
        String contentText = (player != null && player.isPlaying()) ? "Playing..." : "Paused";

        // 构建通知
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID)
                .setContentTitle("Music Player")
                .setContentText(contentText)
                .setSmallIcon(android.R.drawable.ic_media_play)
                .setOngoing(true);

        // 根据播放状态添加相应按钮
        if (player != null && player.isPlaying()) {
            builder.addAction(android.R.drawable.ic_media_pause, "Pause", pausePendingIntent);
        } else {
            builder.addAction(android.R.drawable.ic_media_play, "Play", playPendingIntent);
        }

        builder.addAction(android.R.drawable.ic_menu_close_clear_cancel, "Stop", stopPendingIntent);

        return builder.build();
    }

    // 更新通知
    private void updateNotification() {
        if (notificationManager != null) {
            notificationManager.notify(NOTIFICATION_ID, buildNotification());
        }
    }

    // 广播接收器处理媒体控制
    private final BroadcastReceiver mediaControlReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (ACTION_PLAY.equals(action)) {
                resumeMedia();
            } else if (ACTION_PAUSE.equals(action)) {
                pauseMedia();
            } else if (ACTION_STOP.equals(action)) {
                stopSelf();
            }
        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (player != null) {
            player.release();
            player = null;
        }
        // 隐藏通知
        if (notificationManager != null) {
            notificationManager.cancel(NOTIFICATION_ID);
        }
        // 注销广播接收器（如果已注册）
        try {
            unregisterReceiver(mediaControlReceiver);
        } catch (IllegalArgumentException e) {
            // 接收器未注册，忽略异常
        }
    }
}